package xiang.weiyu.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import xiang.weiyu.common.BaseContext;
import xiang.weiyu.common.R;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//filterName拦截器名称(可写可不写),urlPatterns拦截范围 默认("")内可以直接书写
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Component
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器,支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //将ServletRequest/ServletResponse向下转型为HttpServletRequest/HttpServletResponse.方便调用获取路径URI的方法
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取本次请求的uri并进行判断
        String requestURI = request.getRequestURI();//  /backend/index.html

        //请求资源放行：登录相关的、退出登录相关的、静态资源【html、css 、js 、图片】
        String[] urls = {"/employee/login", "/employee/logout",
                "/backend/**", "/front/**","/common/**","/user/login",
                "/user/sendMsg"
        };
        //调用自定义的路径匹配器方法，
        boolean check = check(urls, requestURI);

        //为true说明该路径不需要处理并放行本次请求路径
        if (check) {
            filterChain.doFilter(request, response);
            return;
        }
        //(管理端)获取请求中的信息,session不为空则说明已经登录了,全部放行,并且结束本次过滤器的过滤
        if (request.getSession().getAttribute("employee") != null) {
            //调用自定义好的静态方法,将session中的id数据存入ThreadLocal线程副本中方便其他方法调用(公共字段注入)
            Long userId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }
        //(移动端)获取请求中的信息,session不为空则说明已经登录了,全部放行,并且结束本次过滤器的过滤
        if (request.getSession().getAttribute("user") != null) {
            //调用自定义好的静态方法,将session中的id数据存入ThreadLocal线程副本中方便其他方法调用(公共字段注入)
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }

        //未登录,不放行,通过输出流向客户端发送响应数据,返回未登录的信息要与前端协商好
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean check = PATH_MATCHER.match(url, requestURI);
            if (check) {
                return true;
            }
        }
        return false;
    }
}
